import 'package:flutter/material.dart';
import '../model/cart.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class CartProvide with ChangeNotifier {
  List<Cart> _cartsList = [];
  int _allCount = 0;
  double _allPrice = 0;

  get cartsList => _cartsList;
  get allCount => _allCount;
  get allPrice => _allPrice;

  getCartsList() async {
    // 从本地取出
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var cartInfoStr = prefs.getString('cartInfo');
    var temp = cartInfoStr == null ? [] : json.decode(cartInfoStr);

    //1、获取仓库中原有的购物车列表
    List<Map> carts = (temp as List).cast();
    _cartsList.clear();
    _allPrice = 0;
    _allCount = 0;
    carts.forEach((item) {
      _allPrice += item['goodsPrice'] * item['count'];
      _allCount += item['count'];
      _cartsList.add(Cart.fromJson(item));
    });

    notifyListeners();
  }

  // 加入购物车
  addToCart(Cart cart) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var cartInfoStr = prefs.getString('cartInfo');
    var temp = cartInfoStr == null ? [] : json.decode(cartInfoStr);

    //1、获取仓库中原有的购物车列表
    List<Map> carts = (temp as List).cast();

    //2、遍历已有的数组，如果有相同的，则数量++，没有则新增
    var _findIndex = -1;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i]['goodsId'] == cart.goodsId) {
        _findIndex = i;
        break;
      }
    }

    if (_findIndex > -1) {
      // 找到了
      carts[_findIndex]['count'] += cart.count;
    } else {
      // 没找到，则新增
      carts.add(cart.toJson());
    }

    // 赋值给_cartsList
    _cartsList.clear();
    _allPrice = 0;
    _allCount = 0;
    carts.forEach((item) {
      _allPrice += item['goodsPrice'] * item['count'];
      _allCount += item['count'];
      _cartsList.add(Cart.fromJson(item));
    });

    // 保存到本地
    prefs.setString('cartInfo', json.encode(carts).toString());

    // 通知
    notifyListeners();
  }

  // 根据id，删除该商品
  deleteGoodsById(String goodsId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var cartInfoStr = prefs.getString('cartInfo');
    var temp = cartInfoStr == null ? [] : json.decode(cartInfoStr);

    //1、获取仓库中原有的购物车列表
    List<Map> carts = (temp as List).cast();

    //2、遍历已有的数组，如果有相同的，则数量++，没有则新增
    var _findIndex = -1;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i]['goodsId'] == goodsId) {
        _findIndex = i;
        break;
      }
    }

    if (_findIndex > -1) {
      // 找到了
      carts.removeAt(_findIndex);
    }

    // 赋值给_cartsList
    _cartsList.clear();
    _allPrice = 0;
    _allCount = 0;
    carts.forEach((item) {
      _allPrice += item['goodsPrice'] * item['count'];
      _allCount += item['count'];
      _cartsList.add(Cart.fromJson(item));
    });

    // 保存到本地
    prefs.setString('cartInfo', json.encode(carts).toString());

    // 通知
    notifyListeners();
  }

  // 更改商品数量
  changeGoodsCountById(String goodsId, String operation) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var cartInfoStr = prefs.getString('cartInfo');
    var temp = cartInfoStr == null ? [] : json.decode(cartInfoStr);

    //1、获取仓库中原有的购物车列表
    List<Map> carts = (temp as List).cast();

    //2、遍历已有的数组，如果有相同的，则数量++，没有则新增
    var _findIndex = -1;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i]['goodsId'] == goodsId) {
        _findIndex = i;
        break;
      }
    }

    if (_findIndex > -1) {
      // 找到了
      if (operation == 'add') {
        carts[_findIndex]['count'] += 1;
      } else if (operation == 'minus') {
        carts[_findIndex]['count'] -= 1;
      }
    }

    // 赋值给_cartsList
    _cartsList.clear();
    _allPrice = 0;
    _allCount = 0;
    carts.forEach((item) {
      _allPrice += item['goodsPrice'] * item['count'];
      _allCount += item['count'];
      _cartsList.add(Cart.fromJson(item));
    });

    // 保存到本地
    prefs.setString('cartInfo', json.encode(carts).toString());

    // 通知
    notifyListeners();
  }

  clearCart() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _allCount = 0;
    notifyListeners();
    await prefs.remove('cartInfo');
  }
}
